package com.pignest.hotel.ui.reception;

import java.util.Date;
import java.util.List;

import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zk.ui.util.Clients;
import org.zkoss.zk.ui.util.GenericAutowireComposer;
import org.zkoss.zul.Button;
import org.zkoss.zul.Checkbox;
import org.zkoss.zul.Label;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Listcell;
import org.zkoss.zul.Listitem;
import org.zkoss.zul.Tab;
import org.zkoss.zul.Textbox;

import com.pignest.framework.util.Utils;
import com.pignest.hotel.beans.Card;
import com.pignest.hotel.beans.Living;
import com.pignest.hotel.beans.LivingSpecifics;
import com.pignest.hotel.beans.Room;
import com.pignest.hotel.beans.RoomType;
import com.pignest.hotel.beans.TbAccounts;
import com.pignest.hotel.definition.InComeItemType;
import com.pignest.hotel.definition.OperateState;
import com.pignest.hotel.definition.RoomLiveStatus;
import com.pignest.hotel.definition.RoomUseStatus;
import com.pignest.hotel.service.CardService;
import com.pignest.hotel.service.MemberService;
import com.pignest.hotel.service.ReceptionService;
import com.pignest.hotel.service.RoomService;
import com.pignest.hotel.system.InComeUtil;
import com.pignest.hotel.util.DateUtil;
import com.pignest.hotel.util.MoneyUtil;
import com.pignest.hotel.util.UIUtils;

public class ChangeRoom extends GenericAutowireComposer {

	/**
	 * 通过查询房间号来换房
	 */
	private static final long serialVersionUID = -28807472959618471L;
	
	private ReceptionService receptionService;
	private RoomService roomService;
	private MemberService memberService;
	private CardService cardService;
	
	private Living living;
	private Room room;
	private Room selectRoom;//选择的房间
	private Button queryBtn;
	private Textbox qRoomName;
	
	private Label roomType;
	private Label roomName;
	private Label roomPrice;
	private Label livingTime;
	private Label roomState;
	
	private Listbox LivingListbox;
	
	private Listbox roomTypeList; //房间类型
	private Listbox selectRoomListbox;
	private Listbox LivingHistoryListbox;
	
	private Textbox newroomName;
	
	private Label currentPrice;//当天房价
	private Label memberPrice;
	private Label currentRoomStatus;
	private int adjustPrice;//不管是会员还是非会员，最后的房价
	private Textbox offsetPrice;
	private Checkbox isOffset;
	private Label changeTip;
	private Listbox changeReason;
	private Button changeRoomBtn;
	private Button readCardBtn;
	private Button grandRoomBtn;
	private Tab LivingHistoryTab;
	
	public void onCreate() {
		queryBtn.addEventListener(Events.ON_CLICK, new EventListener(){
			   public void onEvent(Event event) {
				   query();
			   }
		   });
		roomTypeList.addEventListener(Events.ON_SELECT, new EventListener(){
			   public void onEvent(Event event) {
				   querySelectRoom();
			   }
		   });
		changeRoomBtn.addEventListener(Events.ON_CLICK, new EventListener(){
			   public void onEvent(Event event) {
				   
					change();
					
			   }
		   });
		grandRoomBtn.addEventListener(Events.ON_USER, new EventListener(){
			   public void onEvent(Event event) {
				   String snr =(String)event.getData();
				   if(living==null){
						UIUtils.alert("无效入住！请先查询房间！");
		            	return ;
		            }
				   Card card =null;
				   card =cardService.getCardBySerialNumber(snr);
					if(card==null)
					{
						UIUtils.alert("系统无此卡！");
						return ;
					}
					String c =roomService.checkCard(card,living);
					if(c!=null){
						 if(UIUtils.confirm(c+"\n"+"要取消换房吗？\nNO会造成当前系统中记录卡误写，请谨慎！")){
							  return ;
						  }
					}
					String lockNumber =roomService.getRoom(selectRoom.getId()).getLockNumber();
					if(lockNumber==null||lockNumber.equals(""))
				    {
				        UIUtils.alert("该房间"+selectRoom.getName()+"未配置的门锁号！无法置房卡。请联系管理员或者选择其它房间！");
				        return ;
				    }
					Date d1 =living.getGrantDate();
					String sCardDate=DateUtil.toString(d1,"yyMMddHHmm");
					card.setLockNumber(lockNumber);
					card.setExpireTime(d1);
					cardService.grantCard(snr, selectRoom, d1);
					Clients.evalJavaScript("Card.writeCardMessage('"+snr+"','"+lockNumber+"','"+sCardDate+"',"+null+","+null+",'"+"换房成功"+"')");
				   }
			   });
		readCardBtn.addEventListener(Events.ON_USER, new EventListener(){
			public void onEvent(Event event) {
				readRoomCard(event);
				query();
			}
		});
	}
	public void query(){
		if(qRoomName.getValue()==null||qRoomName.getValue()==""){
			UIUtils.alert("请读取门卡或者输入房间号！");
			return ;
		}else{
			room= roomService.getRoomByName(qRoomName.getValue());
			if(room==null){
				UIUtils.alert("无效的房间号！请输入正确的房间号");
				return ;
			}
		}
		living =receptionService.getLiving(room);
		if(living==null){
			UIUtils.alert("该房间没有入住信息或者已经结账了！");
			return ;
		}
		checkRoomInfo();
		queryLive();
		queryHistoryLiving();
		
	}
	/**
	    * 核对原房间信息
	    * **/
		public void checkRoomInfo(){
			if(living!=null&&room!=null){
				roomType.setValue(room.getType().getName());
				roomName.setValue(room.getName());
				roomPrice.setValue(MoneyUtil.toString(living.getAdjustPrice()));
				livingTime.setValue(DateUtil.toFullString(living.getLiveTime()));
				roomState.setValue(RoomLiveStatus.valueof(room.getLiveStatus()).getName()+RoomUseStatus.valueof(room.getUseStatus()).getName());
			}
		}
		public void queryLive(){
			if(living!=null){
				LivingListbox.getItems().clear();
				Listitem listitem = new Listitem();
				   listitem.setValue(living.getId());
				   listitem.setParent(LivingListbox);
				   listitem.appendChild(new Listcell(living.getRoom().getName()));
				   listitem.appendChild(new Listcell(DateUtil.toString(living.getLiveTime())));
				   listitem.appendChild(new Listcell(living.getCustormName()));
				   listitem.appendChild(new Listcell(RoomLiveStatus.valueof(room.getLiveStatus()).getName()+RoomUseStatus.valueof(room.getUseStatus()).getName()));
				   listitem.appendChild(new Listcell(living.getPhone()));
				   listitem.appendChild(new Listcell(MoneyUtil.toString(living.getStorage())));
				   listitem.appendChild(new Listcell(MoneyUtil.toString(living.getUsed())));
				   listitem.appendChild(new Listcell(MoneyUtil.toString(living.getStorage()-living.getUsed())));
			}
			
		}
		 public void querySelectRoom(){
		    	selectRoomListbox.getItems().clear();
		    	String roomTypeId=UIUtils.getSelectedValue(roomTypeList);
				RoomType roomType =roomService.getRoomType(roomTypeId);
				List <Room>l=roomService.listRooms(RoomLiveStatus.EMPTY,roomType);
				for(final Room r:l){
					Listitem listitem = new Listitem();
					listitem.setParent(selectRoomListbox);
					listitem.appendChild(new Listcell(r.getName()));//房间名
					listitem.appendChild(new Listcell(r.getType().getName()));//房型
					//RoomStatus
					listitem.appendChild(new Listcell(RoomLiveStatus.valueof(r.getLiveStatus()).getName()+RoomUseStatus.valueof(r.getUseStatus()).getName()));//状态
					listitem.appendChild(new Listcell(r.getFloor()));//楼层
					listitem.appendChild(new Listcell(r.getBuilding()));//分栋
					listitem.appendChild(new Listcell(r.getRepairStatus()));//维修状态
					
					listitem.appendChild(new Listcell("是"));//是否可以入住
					listitem.addEventListener(Events.ON_CLICK,  new EventListener(){
						public void onEvent(Event event) throws Exception { 
							setSelectRoom(r);
							setAfterSelectRoom();
						}
					});
					
				}
			}
		 public void queryHistoryLiving(){
			 if(this.living!=null){
					this.LivingHistoryListbox.getItems().clear();
					StringBuffer hql=new StringBuffer();
					hql.append(" from LivingSpecifics b where b.living.id='"+this.living.getId()+"'");
					hql.append(" order by b.operateDate desc");
					List <LivingSpecifics> list=receptionService.find(hql.toString());
					for( LivingSpecifics s:list){
					
					Listitem listitem = new Listitem();
					listitem.setParent(LivingHistoryListbox);
					listitem.appendChild(new Listcell(s.getRoom()));//房间名
					listitem.appendChild(new Listcell(s.getOperateType()));//操作类型
					listitem.appendChild(new Listcell(MoneyUtil.toString(s.getRoomPrice())));//房价
					listitem.appendChild(new Listcell(MoneyUtil.toString(s.getPay())));//金额
					//listitem.appendChild(new Listcell(DateUtil.toString(s.getGrantDate())));//授权时间"
					listitem.appendChild(new Listcell(DateUtil.toString(s.getLeaveDate())));//离开时间
					listitem.appendChild(new Listcell(s.getRemark()));//备注
					listitem.appendChild(new Listcell(DateUtil.toString(s.getOperateDate())));//备注
					}
					
				}
		 }
		    public void setAfterSelectRoom(){
		    	
		    	if(living==null)
		    		return ;
		    	if(selectRoom!=null){
		    		newroomName.setValue(selectRoom.getName());
		    		currentPrice.setValue(MoneyUtil.toString(selectRoom.getType().getPrice()));
		    		currentRoomStatus.setValue(RoomLiveStatus.valueof(selectRoom.getLiveStatus()).getName()+RoomUseStatus.valueof(selectRoom.getUseStatus()).getName());
		    		if(this.living.getMember()!=null){
		    			int i=getMemberPrice(this.living.getMember().getId(),selectRoom.getType().getId());
		    			memberPrice.setValue(MoneyUtil.toString(i));
		    			adjustPrice=i;
		    			offsetPrice(i);
		    		}else{
		    			offsetPrice(selectRoom.getType().getPrice());
		    			adjustPrice=selectRoom.getType().getPrice();
		    		}
		    	}
		    }
		    /**
		     * 换房：
		     * 1、将原来的入住详细信息类型改成换房
		     * 2、新增入住详细信息
		     * ***/
		    public void change(){
		    	try{
		    		if(this.living==null)
		    		{
		    			UIUtils.alert("无效入住！请先查询房间！");
		    			return ;
		    		}
		    	    this.living =receptionService.get(Living.class, living.getId());
		    	    StringBuffer msg = new StringBuffer();
		    		msg.append("你好！").append(living.getCustormName()).append("\n");
		    		
			    	String sChangeReason=UIUtils.getSelectedValue(changeReason);
			    	 LivingSpecifics livingLs=receptionService.querySpec(living);
			    	 livingLs.setOperateType(OperateState.CHANGEROOM.name());
			    	 livingLs.setRemark("由"+livingLs.getRoom()+"换成"+selectRoom.getName());
			    	 livingLs.setLeaveDate(new Date());
			    	 
			    	 LivingSpecifics ls = new LivingSpecifics();
			    	 ls.setLiving(living);
			    	 ls.setOperateDate(new Date());
			    		//ls.setOperateType("换房");
			    	 ls.setOperateType(OperateState.LIVING.name());
			    	 ls.setRoom(selectRoom.getName());
			    	 ls.setRoomPrice(adjustPrice);
			    	
			    	 ls.setRemark(sChangeReason);
			    	 ls.setLeaveDate(this.living.getLeaveDate());
			    	 ls.setGrantDate(this.living.getGrantDate());
			    	 TbAccounts ta=null;
			    	String offsetMsg="";
			    	if(isOffset.isChecked())
			    	{
			    		ta =new TbAccounts();
			    		ta.setLiving(living);
			    		ta.setCounts(1);
			    			//ta.setName("房间调整费");
			    		ta.setName(InComeItemType.FJTZF.getValue());
			    		int iOffsetPrice =Utils.toPrice(offsetPrice.getValue());
			    		 ls.setPay(iOffsetPrice);
			    		ta.setPrice(-iOffsetPrice);
			    		ta.setOptime(new Date());
			    		ta.setType(InComeItemType.FJTZF.name());
			    		 ls.setRoomPrice(iOffsetPrice);
			    		 ls.setRemark(InComeItemType.FJTZF.getValue()+",调整费:"+Utils.toPrice(iOffsetPrice));
			    		ta.setPrice2(iOffsetPrice);
			    		ta.setOpdate(DateUtil.currentDateToString(DateUtil.DEFAULT_DATE_FORMAT));
			    		ta.setEndstate("否");
			    		ta.setRemark("由"+livingLs.getRoom()+"换成"+selectRoom.getName()+"调整费："+Utils.toPrice(iOffsetPrice));
			    		offsetMsg="补偿差价："+Utils.toPrice(iOffsetPrice);
			    	}
			    	msg.append("是否由").append(this.living.getRoom().getName()).append("\n");
			    	msg.append("换成").append(this.selectRoom.getName()).append("\n");
			    	msg.append("当前的房价为:").append(Utils.toPrice(adjustPrice)).append("\n");
			    	msg.append(offsetMsg);
			    	if(UIUtils.confirm(msg.toString())){
		    		   this.living.setRoom(selectRoom);
				    	this.living.setAdjustPrice(adjustPrice);
				    	room.setUseStatus(RoomUseStatus.DIRTY.name());
				    	room.setLiveStatus(RoomLiveStatus.EMPTY.name());
				    	selectRoom.setLiveStatus(RoomLiveStatus.FILLED.name());
				    	receptionService.changeRoom(ls, livingLs,this.living, ta,room,selectRoom);
				    	UIUtils.alert("请给原房卡重新授权!");
				    	grandRoomBtn.setDisabled(false);
				    	qRoomName.setValue(selectRoom.getName());
				    	living =receptionService.get(Living.class, living.getId());
			    		query();
			    		LivingHistoryTab.setSelected(true);
			    		
			    	}
         
		    	}catch(Exception e){
		    		UIUtils.alert("异常!");
		    		e.printStackTrace();
		    	}
		    }	    
      public Room getSelectRoom()
      {
		return selectRoom;
	  }
	  public void setSelectRoom(Room selectRoom) 
	  {
		this.selectRoom = selectRoom;
	  }
	  public int getMemberPrice(String MemberId,String roomId)
	  {
	    	return memberService.getMemberPrice(MemberId, roomId);
	  }
	  public void offsetPrice(int curprice){
	    	int oPrice =this.living.getAdjustPrice();
	    	int offset=0;
	    	if(curprice<oPrice)
	    	{
	    		 offset= oPrice-curprice;
	    		 isOffset.setChecked(true);
	    		 offsetPrice.setValue(Utils.toPrice(offset));
	    		 changeTip.setValue("建议补偿差价："+Utils.toPrice(offset));
	    	}else
	    	{
	    		isOffset.setChecked(false);
	    		offsetPrice.setValue("0");
	    		changeTip.setValue("");
	    	}
	    	
	    }
	  public void readRoomCard(Event event){
			String lockNumber =(String)event.getData();
			if(lockNumber.equals("")||lockNumber==null){
				UIUtils.alert("请将门卡读卡器上！");
				return ;
			}
			Room room =roomService.getRoomByLock(lockNumber);
			if(room==null)
			{
				UIUtils.alert("无此房间,或者无设置门锁号！请手动输入房间号,锁号："+lockNumber);
				return ;
			}
			qRoomName.setValue(room.getName());
		}
	 

}
